import axios from 'axios';
import store from '../store';
import config from './config';
import router from '@/router'
import { MessageBox, Message } from 'element-ui'
import { getStorage, setStorage, removeStorage } from '@/utils/auth'
import JSEncrypt from "jsencrypt"

const interfaceApi = axios.create({
	timeout: config.api.overtime,
	baseURL: config.api.url
});
//请求拦截
interfaceApi.interceptors.request.use((options) => {
	options.url = config.api.url + options.url

	if (store.state.user.token) {
		options.headers.Authorization = 'Bearer ' + store.state.user.token;
	}
	return options;
});

//响应拦截
interfaceApi.interceptors.response.use((response) => {
	if (response.status != 200) {
		return Promise.reject("系统异常2")
	}

	if (!response) {
		Message.error("网络错误")
		return Promise.reject("网络错误")
	}


	if (!response) {
		Message.error("系统异常3")
		return Promise.reject("系统异常3")
	}


	if (!(response.data.code == config.api.nodectyptCode) && config.encryption) {
		//不等于201才解密
		//解密请求到的数据
		let decrypt = new JSEncrypt();

		decrypt.setPrivateKey(config.cert.privateKey);
		var decryptMsg = decrypt.decryptLong(response.data, 'utf-8');
		response = JSON.parse(decryptMsg);

			console.log('response',response)
		//不等于200并且不等于401提示异常
		// if (response.code != 200 && response.code != 401  ) {
		// 	Message.error(response.message)
		// }

        //code303表示没有实名认证，需要跳实名认证
		if(response.code == 303){
			router.push({ path: "/?visible=" + true });
			return
		}

		if(response.code == 402){
			console.log('渐入')
			Message.error('账号已封禁　' + ' 封禁理由：　' + response.data.message + ' 请联系陪秀管理员：' + response.data.contact)
				return Promise.reject(response.data.message)
			
		}

		if (response[config.api.codeField] == config.api.overdueCode) {
			removeStorage('Authorization') // must remove  token  first
			removeStorage('hasLogin') // must remove  token  first
			removeStorage('userInfo') // must remove  token  first
			MessageBox.confirm(
				'登录状态已过期，您可以继续留在该页面，或者重新登录',
				'系统提示',
				{
					confirmButtonText: '重新登录',
					cancelButtonText: '取消',
					type: 'warning'
				}
			).then(() => {
				store.dispatch('user/logout').then(() => {
					location.reload() // 为了重新实例化vue-router对象 避免bug
				})
			})
		}

		if (response[config.api.codeField] != config.api.successCode && response[config.api.codeField] != config.api.nodectyptCode) {
			Message.error(response[config.api.messgaeField] || '系统异常4')
			return Promise.reject(response[config.api.messgaeField] || '系统异常4')
		}


		return response[config.api.resultField] || response;
	} else {
		if (response.data[config.api.codeField] == config.api.overdueCode) {
			removeStorage('Authorization') // must remove  token  first
			removeStorage('hasLogin') // must remove  token  first
			removeStorage('userInfo') // must remove  token  first
			MessageBox.confirm(
				'登录状态已过期，您可以继续留在该页面，或者重新登录',
				'系统提示',
				{
					confirmButtonText: '重新登录',
					cancelButtonText: '取消',
					type: 'warning'
				}
			).then(() => {
				store.dispatch('user/logout').then(() => {
					location.reload() // 为了重新实例化vue-router对象 避免bug
				})
			})
		}


		if (response.data[config.api.codeField] != config.api.successCode && response.data[config.api.codeField] != config.api.nodectyptCode) {
			Message.error(response.data[config.api.messgaeField] || '系统异常4')
			return Promise.reject(response.data[config.api.messgaeField] || '系统异常4')
		}

		return response.data[config.api.resultField] || response.data;
	}





}, error => {
	return Promise.reject("系统异常5")
});

const request = async (url, data, method, isLoading = false, headers) => {

	// 对需要加密的数据进行加密
	const encryptor = new JSEncrypt()
	encryptor.setPublicKey(config.cert.publicKey) // 设置公钥
	let encryptedData = encryptor.encryptLong(JSON.stringify(data))
	data = {
		request_data: encryptedData
	}
	if (isLoading) {
		store.commit('data/loading', true);
	}

	return new Promise(async (resolve, reject) => {

		interfaceApi.request({
			method,
			url,
			data: method != 'get' && data,
			params: method == "get" && data,
		}).then(res => resolve(res))
			.catch(error => {

				reject(error);
			}).finally(() => {
				if (isLoading) {
					store.commit('data/loading', false);
				}
			})

	})

}


export const get = (url, data = {}, loading = false) => {
	return request(url, data, 'get', loading);
}

export const post = (url, data = {}, loading = false) => {
	return request(url, data, 'post', loading);
}

export const put = (url, data = {}, loading = false) => {
	return request(url, data, 'put', loading);
}

export const del = (url, data = {}, loading = false) => {
	return request(url, data, 'delete', loading);
}

export const upload = (url, data = {}, loading = false) => {

	const formData = new FormData();

	for (let key in data) {
		formData.append(key, data[key]);
	}

	return request(url, formData, 'post', loading, { "Content-Type": "multipart/form-data" });
}


export default {
	get, post, put, del, upload
}